<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/12
 * Time: 16:10
 */
namespace App\Models;

Class Member extends BaseModel{

    protected $table = 'member';
    public $timestamps = false;

    public function __construct( )
    {
        parent::__construct();
    }

    /**
     * 按条件查询单条数据
     */
    public function getOne(array $where, $fields = '*')
    {
        return $this->multiSelect($fields)->multiWhere($where)->first();
    }

    /**
     * 按条件查询全部数据,根据配置显示条数显示
     */
    public function getList(array $where = [], $fields = '*', $order = '', $pageSize = '')
    {
        if ($pageSize) {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->paginate($pageSize);
        } else {
            return $this->multiSelect($fields)->multiWhere($where)->multiOrder($order)->get();
        }
    }

    /**
     * 根据条件删除数据
     */
    public function del(array $where)
    {
        return $this->multiWhere($where)->delete();
    }

    /**
     *插入数据
     */
    public function add($data)
    {
//        dd($data);
        return $this->insertGetId($data);
    }

    /**
     *更新数据
     */
    public function up($where, $data)
    {
        return $this->multiWhere($where)->update($data);
    }

    /**
     * 获取和
     */
    public function getSum($where, $field)
    {
        return $this->multiWhere($where)->sum($field);
    }

    /**
     * 字段递加
     */
    public function inc($where, $field, $n)
    {
        return $this->multiWhere($where)->increment($field, $n);
    }

    /**
     * 登录
     */
    public function logindo($request){
        $username = $request['username'];
        $password = $request['password'];
        if (empty($username) || empty($password)) {
            $res['code'] = 400;
            $res['msg']  = '账号和密码不能为空';
            return $res;
        }
        $where['username'] = $username;
        $resulte = $this->getOne($where);
        if (empty($resulte)){
            $res['code'] = 400;
            $res['msg']  = '账号或密码错误';
            return $res;
        }
        if ($resulte['password'] != md5($password)) {
            $res['code'] = 400;
            $res['msg']  = '账号或密码错误';
            return $res;
        }

        /**
         * 更新Ip
         */
        $updata['lastlogip'] = get_client_ip();
        $updata['lastlogtime'] = time();
        $this->up(['id'=>$resulte['id']],$updata);
        $res['code'] = 200;
        $res['msg']  = '登录成功';
        $this->loginStep2($resulte);
        addSession('loginId',$resulte['id']);
        return $res;
    }

    /**
     * 登录第二步 写日志
     */
    public function loginStep2($d){
        // 判断是否为当天第一次登录
        $where['datey'] = date('y',time());
        $where['datem'] = date('m',time());
        $where['dated'] = date('d',time());
        $logsModel = new login_log();
        $logs = $logsModel->getOne($where);
        if (!$logs){
            // 这里为当天第一次登录 处理逻辑
            $updata['experience'] = $d['experience'] + 5;
            $this->up(['id'=>$d['id']],$updata);
        }
        $data['uid'] = $d['id'];
        $data['logintime'] = time();
        $data['datey'] = date('y',time());
        $data['datem'] = date('m',time());
        $data['dated'] = date('d',time());
        $logsModel->add($data);
    }

    /**
     * 注册第一步
     * @param $req
     * @return mixed
     */
    public function regster_step1($req){
        $username = $req['username'];
        $password = $req['password'];
        $res['code'] = 200;
        $res['msg']  = 'ok';
        addSession('loginId',1);
        return $res;
        die;
        if (empty($username) || empty($password)){
            $res['code'] = 400;
            $res['msg']  = '用户名和密码不能为空';
            return $res;
        }
        $user = $this->getOne(['username'=>$username]);
        if ($user) {
            $res['code'] = 400;
            $res['msg']  = '该账号已存在';
            return $res;
        }
        $data['username'] = $username;
        $data['password'] = md5($password);
        $data['used'] = 0; // 账号不可用
        $resulte = $this->add($data);
        if ($resulte) {
            $res['code'] = 200;
            $res['msg']  = 'ok';
            addSession('loginId',$resulte);
            return $res;
        }
    }

    /**
     * 注册账号第二步
     * @param $request
     * @return mixed
     */
    public function regster_step2($request){
         $loginId = session('loginId');
         $nickname = $request['nickname'];
         $birthday = $request['birthday'];
         $qq       = $request['qq'];
         if (empty($nickname)){
             $res['code'] = 400;
             $res['msg']  = '昵称不能为空';
             return $res;
         }
         $data['nickname'] = $nickname;
         $data['birthday'] = $birthday;
         $data['qq']       = $qq;
         $data['used']     = 1;
         if ($this->up(['id'=>$loginId],$data)) {
              $res['code'] = 200;
              $res['msg']  = '注册成功';
              return $res;
         }
         $res['code'] = 400;
         $res['msg']  = '注册失败';
         return $res;
    }

    /**
     * 返回用户信息 [根据条件]
     * @param $field
     * @param $where
     * @return mixed
     */
    public function memberInfo($field,$where){
         $where['used'] = 1;
         return $this->getOne($where,$field)->toArray();
    }

    /**
     * 获取等级信息
     * 当前等级
     * 据下一级还差多少
     * 下一级
     */
    public function getLevelInfo($u){
          $levelConfig = config('level.common');
          foreach ($levelConfig as $v) {
              if ($v['minExp']<$u['experience'] && $v['maxExp']>$u['experience']){
                    $level['remain'] = $v['maxExp']-$u['experience'];
                    $level['nextlevel'] = $u['level_common']+1;
                    $level['percent'] = $u['experience']/$v['maxExp'];
                    return $level;
              }
          }
    }

    /**
     * 获取等级信息
     * 当前等级
     * 据下一级还差多少
     * 下一级
     */
    public function getLevelInfoForZhubo($u){
        $levelConfig = config('level.zhubo');
        foreach ($levelConfig as $v) {
            if ($v['mingift']<$u['gift'] && $v['maxgift']>$u['gift']){
                $level['remain'] = $v['maxgift']-$u['gift'];
                $level['nextlevel'] = $u['level_zhubo']+1;
                $level['percent'] = $u['gift']/$v['maxgift'];
                return $level;
            }
        }
    }

    /**
     * 获取主播相关信息
     */
    public function getZhuboInfo($u){
         // 获取主播房间信息
         $roomModel = new Roomnum();
         $roomCategroy = new Roomcategroy();
         $liveRecordModel = new Liverecord();
         $room = $roomModel->getOne(['uid'=>$u['id']]);
         $room['catename'] = $roomCategroy->getOne(['id'=>$room['cate']],'catename');
         // 获取主播上次直播记录
         $liverecords = $liveRecordModel->getList(['roomnum'=>$room['num']],'',['starttime'=>'desc'],1);
         if ($liverecords){
              $liverecords = $liverecords->toArray()['data'];
              // 计算直播时间
              $min = intval(($liverecords[0]['endtime'] - $liverecords[0]['starttime']));
              $liverecords[0]['min'] = timeFormat($min);
         }
         $room['livehistory'] = $liverecords;
         // 计算主播等级
         $level = $this->getLevelInfoForZhubo($u);
         $room['zhubo'] = $level;
         return $room;
    }

    /**
     * 检测是否足够赠送该礼物
     */
    public function isSendgift($gid){
        $member = $this->memberInfo('*',['id'=>session('loginId')]);
        $giftModel = new Gift();
        $gift = $giftModel->getOne(['id'=>$gid]);
        if ($member['m']<$gift['needcoin']){
               return ['code'=>400,'msg'=>'您的M币不足'];
        }else{
            return ['code'=>200,'msg'=>'ok'];
        }
    }

    /**
     * 获取登录用户信息
     */
    public function userInit(){
        $login = session('loginId');
        if ($login) {
            $field = '*';
            $where['id'] = $login;
            $userinfo = $this->memberInfo($field,$where);
            $userinfo['islogin'] = true;
        }else{
            $userinfo['islogin'] = false;
        }
        return $userinfo;
    }

    /**
     * 上传头像
     */
    public function uploadface(){
        $loginId = session('loginId');
        $base = $_POST['imagedata'];
        if (empty($base)){
              return ['code'=>400,'msg'=>"请上传图片数据"];
        }
        // 保存文件地址
        $dir = 'upload/user_face/'.$loginId;
        $image[] = $base;
        $res = upImgs($image,$dir);
        if (empty($res)) {
             return ['code'=>400,'msg'=>"上传错误"];
        }
        // 生成缩略图
        $thumb_width = 200;
        $thumb_height = 200;
        $sourceimage = $res[0];
        $fix = get_extension($sourceimage);
        $filename = basename($sourceimage,".".$fix);
        $new_dir = $dir."/".$filename."_".$thumb_width."_".$thumb_height.".".$fix;
        $thumb_images = resize($sourceimage,$new_dir,$thumb_width,$thumb_height);
        if (empty($thumb_images)) {
            return ['code'=>400,'msg'=>"生成缩略图错误"];
        }
        $memberupdata['bigpic'] = $new_dir;
        $res = $this->up(['id'=>$loginId],$memberupdata);
        if ($res) {
             return ['code'=>'200','msg'=>'图片上传成功'];
        }
        return ['code'=>'400','msg'=>'图片上传失败'];
    }

    /**
     * 修改基本信息
     */
    public function uploadmemberinfo($req){
        $loginId = session('loginId');
        $memberupdata['realname'] = $req['realname'];
        $memberupdata['sex'] = $req['sex'];
        $memberupdata['birthday'] = $req['birthday'];
        $memberupdata['qq'] = $req['qq'];
        $memberupdata['weixin'] = $req['weixin'];
        $memberupdata['interest'] = $req['interest'];
        $res = $this->up(['id'=>$loginId],$memberupdata);
        if ($res) {
             return ['code'=>200,'msg'=>'修改成功'];
        }
        return ['code'=>400,'msg'=>'修改失败'];
    }

}